/*
	省市区三级联动
	格式：rel='{"province":3133,"city":3218,"county":3219}'
*/
var region = function(dom) {
    var self = this;
    this.dom = dom;
    this.json = cityJson; //加载省市区数据
    this.pro = $(dom.find('select')[0]); //省
    this.city = $(dom.find('select')[1]); //市
    this.county = $(dom.find('select')[2]); //区
    this.set = this.getSetting(); //获取默认数据
    if (this.set != null) {
        this.loadPro(this.set.province);
        this.LoadCity(this.set.city);
        this.LoadCounty(this.set.county);
    } else {
        //加载省
        this.loadPro();
    }
    //选择当前，加载下一项
    this.pro.change(function() {
        self.LoadCity();
        //self.LoadCounty();
    });
    this.city.change(function() {
        self.LoadCounty();
    });
};
region.prototype = {
    //加载省
    loadPro: function(proId) {
        this.pro.html(this.readData(this.json));
        if (proId) {
            this.pro.val(proId);
        }
    },
    //根据省加载市
    LoadCity: function(cityId) {
        var proId = this.pro.get(0).selectedIndex,
            citys = this.json[proId - 1];
        if (proId === 0) {
            this.city.html('<option value="0">请选择</option>');
            this.county.html('<option value="0">请选择</option>');
            return false;
        }
        this.city.html(this.readData(citys.cities));
        this.LoadCounty();
        if (cityId) {
            this.city.val(cityId);
        }
    },
    //根据市加载区
    LoadCounty: function(countyId) {
        var proId = this.pro.get(0).selectedIndex,
            cityId = this.city.get(0).selectedIndex,
            citys = this.json[proId - 1];
        if (cityId === 0) {

            this.county.html('<option value="0">请选择</option>');
            return false;
        }
        this.county.html(this.readData(citys.cities[cityId - 1].counties));
        if (countyId) {
            this.county.val(countyId);
        }
    },
    //渲染数据
    readData: function(data) {
        var html = '<option value="0">请选择</option>';
        $.each(data, function(index, el) {
            html += '<option value="' + el.id + '">' + el.region_name + '</option>';
        });
        return html;
    },
    //获取默认参数
    getSetting: function() {
        var setting = this.dom.attr("rel");
        if (setting && setting !== "") {
            setting = setting.replace("[", "{");
            setting = setting.replace("]", "}");
            return $.parseJSON(setting);
        } else {
            return null;
        }
    }
};
region.init = function(dom) {
    var _this = this;
    dom.each(function(i, v) {
        new _this($(v));
    });
};
